"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
  User,
  Lock,
  Mail,
  Eye,
  EyeOff,
  Briefcase,
  CheckCircle,
  AlertCircle,
  UserPlus,
  ArrowLeft
} from "lucide-react"

export default function LoginPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    email: "",
    password: ""
  })
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [isLoginMode, setIsLoginMode] = useState(true)

  // 注册表单数据
  const [registerData, setRegisterData] = useState({
    name: "",
    email: "",
    password: "",
    confirmPassword: "",
    company: "",
    phone: ""
  })

  useEffect(() => {
    // 检查是否已经登录
    const user = localStorage.getItem('currentUser')
    if (user) {
      router.push('/')
    }
  }, [router])

  const handleInputChange = (field: string, value: string) => {
    if (isLoginMode) {
      setFormData(prev => ({ ...prev, [field]: value }))
    } else {
      setRegisterData(prev => ({ ...prev, [field]: value }))
    }
    setError("")
  }

  const validateForm = () => {
    if (isLoginMode) {
      if (!formData.email || !formData.password) {
        setError("请填写完整的登录信息")
        return false
      }
      if (!formData.email.includes('@')) {
        setError("请输入有效的邮箱地址")
        return false
      }
    } else {
      if (!registerData.name || !registerData.email || !registerData.password || !registerData.confirmPassword) {
        setError("请填写完整的注册信息")
        return false
      }
      if (!registerData.email.includes('@')) {
        setError("请输入有效的邮箱地址")
        return false
      }
      if (registerData.password.length < 6) {
        setError("密码长度至少6位")
        return false
      }
      if (registerData.password !== registerData.confirmPassword) {
        setError("两次输入的密码不一致")
        return false
      }
    }
    return true
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validateForm()) return

    setLoading(true)
    setError("")

    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500))

      if (isLoginMode) {
        // 登录逻辑
        const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
        const user = users.find((u: any) => u.email === formData.email && u.password === formData.password)
        
        if (user) {
          // 登录成功
          const loginUser = {
            id: user.id,
            name: user.name,
            email: user.email,
            company: user.company,
            phone: user.phone,
            loginTime: new Date().toISOString()
          }
          localStorage.setItem('currentUser', JSON.stringify(loginUser))
          router.push('/')
        } else {
          setError("邮箱或密码错误")
        }
      } else {
        // 注册逻辑
        const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
        
        // 检查邮箱是否已存在
        if (users.some((u: any) => u.email === registerData.email)) {
          setError("该邮箱已被注册")
          return
        }

        // 创建新用户
        const newUser = {
          id: Date.now().toString(),
          name: registerData.name,
          email: registerData.email,
          password: registerData.password,
          company: registerData.company,
          phone: registerData.phone,
          registerTime: new Date().toISOString()
        }

        users.push(newUser)
        localStorage.setItem('registeredUsers', JSON.stringify(users))

        // 自动登录
        const loginUser = {
          id: newUser.id,
          name: newUser.name,
          email: newUser.email,
          company: newUser.company,
          phone: newUser.phone,
          loginTime: new Date().toISOString()
        }
        localStorage.setItem('currentUser', JSON.stringify(loginUser))
        router.push('/')
      }
    } catch (error) {
      setError("操作失败，请稍后重试")
    } finally {
      setLoading(false)
    }
  }

  const switchMode = () => {
    setIsLoginMode(!isLoginMode)
    setError("")
    setFormData({ email: "", password: "" })
    setRegisterData({
      name: "",
      email: "",
      password: "",
      confirmPassword: "",
      company: "",
      phone: ""
    })
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-amber-50/20 to-slate-100/30 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* 返回首页按钮 */}
        <Button
          variant="ghost"
          className="mb-6"
          onClick={() => router.push("/")}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回首页
        </Button>

        <Card className="bg-white/80 backdrop-blur-sm border-0 shadow-xl">
          <CardHeader className="text-center pb-6">
            <div className="w-16 h-16 bg-gradient-to-br from-slate-700 to-slate-900 rounded-full flex items-center justify-center mx-auto mb-4">
              <Briefcase className="w-8 h-8 text-amber-400" />
            </div>
            <CardTitle className="text-2xl font-bold text-slate-900">
              {isLoginMode ? "欢迎回来" : "加入创业者之家"}
            </CardTitle>
            <p className="text-slate-600 mt-2">
              {isLoginMode ? "登录您的账户，继续创业之旅" : "注册账户，开启您的创业之旅"}
            </p>
          </CardHeader>

          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              {!isLoginMode && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      姓名 *
                    </label>
                    <div className="relative">
                      <User className="w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400" />
                      <Input
                        placeholder="请输入您的姓名"
                        value={registerData.name}
                        onChange={(e) => handleInputChange("name", e.target.value)}
                        className="pl-10"
                        disabled={loading}
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      公司名称
                    </label>
                    <div className="relative">
                      <Briefcase className="w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400" />
                      <Input
                        placeholder="请输入公司名称（选填）"
                        value={registerData.company}
                        onChange={(e) => handleInputChange("company", e.target.value)}
                        className="pl-10"
                        disabled={loading}
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      手机号码
                    </label>
                    <Input
                      placeholder="请输入手机号码（选填）"
                      value={registerData.phone}
                      onChange={(e) => handleInputChange("phone", e.target.value)}
                      disabled={loading}
                    />
                  </div>
                </>
              )}

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">
                  邮箱地址 *
                </label>
                <div className="relative">
                  <Mail className="w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400" />
                  <Input
                    type="email"
                    placeholder="请输入邮箱地址"
                    value={isLoginMode ? formData.email : registerData.email}
                    onChange={(e) => handleInputChange("email", e.target.value)}
                    className="pl-10"
                    disabled={loading}
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">
                  密码 *
                </label>
                <div className="relative">
                  <Lock className="w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400" />
                  <Input
                    type={showPassword ? "text" : "password"}
                    placeholder={isLoginMode ? "请输入密码" : "请输入密码（至少6位）"}
                    value={isLoginMode ? formData.password : registerData.password}
                    onChange={(e) => handleInputChange("password", e.target.value)}
                    className="pl-10 pr-10"
                    disabled={loading}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600"
                    disabled={loading}
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {!isLoginMode && (
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-2">
                    确认密码 *
                  </label>
                  <div className="relative">
                    <Lock className="w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400" />
                    <Input
                      type="password"
                      placeholder="请再次输入密码"
                      value={registerData.confirmPassword}
                      onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
                      className="pl-10"
                      disabled={loading}
                    />
                  </div>
                </div>
              )}

              {error && (
                <Alert className="border-red-200 bg-red-50">
                  <AlertCircle className="h-4 w-4 text-red-600" />
                  <AlertDescription className="text-red-700">
                    {error}
                  </AlertDescription>
                </Alert>
              )}

              <Button
                type="submit"
                className="w-full bg-slate-700 hover:bg-slate-800 text-white"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                    {isLoginMode ? "登录中..." : "注册中..."}
                  </>
                ) : (
                  <>
                    {isLoginMode ? (
                      <User className="w-4 h-4 mr-2" />
                    ) : (
                      <UserPlus className="w-4 h-4 mr-2" />
                    )}
                    {isLoginMode ? "登录" : "注册"}
                  </>
                )}
              </Button>
            </form>

            <div className="mt-6 text-center">
              <span className="text-slate-600 text-sm">
                {isLoginMode ? "还没有账户？" : "已有账户？"}
              </span>
              <button
                onClick={switchMode}
                className="ml-2 text-amber-600 hover:text-amber-700 text-sm font-medium"
                disabled={loading}
              >
                {isLoginMode ? "立即注册" : "立即登录"}
              </button>
            </div>

            {/* 体验功能说明 */}
            <div className="mt-6 p-4 bg-amber-50 rounded-lg">
              <div className="flex items-start space-x-2">
                <CheckCircle className="w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0" />
                <div>
                  <h4 className="font-medium text-amber-900 mb-1">注册后您可以：</h4>
                  <ul className="text-sm text-amber-700 space-y-1">
                    <li>• 使用所有创业工具和分析功能</li>
                    <li>• 保存和管理您的项目数据</li>
                    <li>• 参与社区交流和活动</li>
                    <li>• 获取个性化推荐和服务</li>
                  </ul>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
